
define(function(require, exports, module) {

    "use strict";
    var config = require("config"),
        Defer = require("defer");


    var result = {};

    // 获取页面参数
    result.getQueryParms = function(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        }
        return null;
    }

    result.ajax = function(url, jsonParam, obj) {

        var defer = Defer(),
            obj = obj || {}, // ajax 其他参数
            cacheResult, // 已缓存结果
            ajaxJquery,
            option = {};

        option.url = config.baseUrl + url;
        option.type = obj.type || "get";
        option.data = jsonParam || {};

        // 上线自动注释掉
        if(_dev){option.data.dev = _dev;}

        // 临时缓存结果
        if (obj.cache && (cacheResult = _session.getItem(JSON.stringify(option))) ) {
            defer.resolve($.extend(true, {}, JSON.parse(cacheResult)));
        } else {
            ajaxJquery = $.ajax({
                url: option.url,
                timeout: config.ajaxtimeout,
                type: option.type,
                data: option.data,
                dataType: "json",
                async: true,
                success: function(json) {
                    // console.log(json);
                    if (json) {
                        if (obj.returnAll) {
                            defer.resolve(json);
                            return;
                        }
                        if (json.status === 0) {
                            defer.resolve(json);
                        } else if (json.status === -100){
                            // 未登录
                            window.location.href = "login.html";
                            defer.reject(json);
                        } else {
                            defer.reject(json);
                            result.alert(json.message);
                            // console.error("业务异常：" + url);
                            // console.log(json);
                        }
                    } else {
                        defer.reject();
                        result.alert("解析异常");
                    }
                },
                error: function(xhr, error) {
                    if (error === "abort") return;

                    if (error === "parsererror") {
                        defer.reject();
                        result.alert("解析异常");
                    } else {
                        // if (error !== "timeout") {}
                        // console.error("请求异常：" + url);
                        result.alert("网络异常");
                        defer.reject();
                    }
                }
            });

        }

        defer.abort = function() {
            ajaxJquery && ajaxJquery.abort();
            // result.alert("取消请求");
            defer.reject();
        }


        return defer;
    };


    // 去除前后空格
    result.trim = function(str) {
        str = (typeof str === "string") ? str.replace(/(^\s*)|(\s*$)/g, "") : str;
        return str;
    }

    // 判断什么是数字
    result.isNumber = function(obj) {
        obj = +obj;
        return typeof obj === 'number' && !isNaN(obj)
    }

    // 改变时间格式
    result.changeTime = function(str, format) {
        if (!str) return "";
        if (!format) {
            format = "yyyy-mm-dd"; //  hh:ii
        };
        var date;
        if (typeof str === "string") {
            date = new Date(str.replace(/-/g, "/").replace(/T/g, " ").replace(/\+.*$/g, ""));
        } else {
            date = str;
        }

        var objForReplace = {
            y: function(length) {
                length = length < 2 ? 4 : length;
                return date.getFullYear().toString().slice(4 - length, 4);
            },
            m: function() {
                var s = date.getMonth() + 1 + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            d: function() {
                var s = date.getDate() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            h: function() {
                var s = date.getHours() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            i: function() {
                var s = date.getMinutes() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s
            },
            s: function() {
                var s = date.getSeconds() + "";
                if (s.length < 2) {
                    s = "0" + s;
                }
                return s;
            },
            w: function() {
                var s = date.getDay();
                return "周" + "日一二三四五六".charAt(s);
            },
            p: function() {
                var s = date.getDay();
                return "6012345".charAt(s);;
            }
        };
        var reg = /y+|m+|d+|h+|i+|s+|w+|p+/gi
        var rtStr = format.replace(reg, function(r) {
            var len = r.length;
            var type = r.charAt(0);
            return objForReplace[type](len);
        });

        return rtStr;
    }

    // arr : {val:, type:, tip:}
    result.checkVal = function(arr){
        if (!arr) return null;

        var r = {flag: true, tip: ""},
            i = 0, la = arr.length,
            j = 0, lb,
            v, typeArr, type;

        for (; i < la; i++) {
            if (!r.flag) break;

            v = arr[i];
            v.val = result.trim(v.val);
            j = 0;
            typeArr = v.type.split(",");
            lb = typeArr.length;

            for (; j < lb; j++) {
                if (!r.flag) break;
                type = typeArr[j];
                // console.log(config.patternObj[type].regexp, v.val);
                if( config.patternObj[type] && !config.patternObj[type].regexp.test(v.val) ){
                    r.flag = false;
                    r.tip = !v.tip ? config.patternObj[type].tip : v.tip;
                }
            }
        }

        return r;
    }

    // 倒计时
    result.exCountDonwTime = function(o) {
        var coutTime = (o.time || 0) * 1000;
        var countstartTime = new Date();
        var time, r = {},
            newTime, isOver = false;

        function countRun() {
            if (isOver) return;
            newTime = new Date();
            var guoqu = coutTime - (newTime - countstartTime);
            if (guoqu > 0) {
                o.runFn && o.runFn(parseInt(guoqu / 1000, 10));
                time = setTimeout(countRun, 550);
            } else {
                r.stop();
            }
        }
        r.stop = function(flag) {
            if (isOver) return;
            isOver = true;
            clearTimeout(time);
            !flag && o.callback && o.callback(o.time);
            return parseInt((newTime - countstartTime) / 1000);
        }
        countRun();
        return r;
    }

    var $tool = $("#J__m_tooltips");
    result.alert = function(mess, time) {
        var defer = Defer();
        if ($tool.length) {
            $tool.find(".tooltip-text").html(mess);
        } else {
            $tool = $('<div id="J__m_tooltips" class="m_tooltips none"/>');
            $('<div class="tooltip-text tooltip-content"/>').html(mess).appendTo($tool);
            $tool.appendTo('body');
        }

        $tool.removeClass("none");
        $tool.get(0).offsetHeight;
        $tool.addClass("on");

        time = time || 2500;
        setTimeout(function() {
            $tool.removeClass("on");
            $tool.addClass("none");
            defer.resolve();
        }, time);
        return defer;
    }

    // loading
    result.loading = {
        $loaiing: $("#J__m_loading"),
        show: function(mess, type) {
            mess = (mess ? mess : '加载中');
            if (this.$loaiing.length) {
                this.$loaiing.find(".J__loadingmess").html(mess);
            } else {
                this.$loaiing = $('<div id="J__loadingF" class="m_loading"/>');
                this.$loaiing.html('<div><div class="loading__img"></div><div class="loading__mess"><span class="J__loadingmess">' + mess + '</span><span class="dotloading"></span></div></div>').appendTo('body');
            }
            this.$loaiing.addClass("on");
        },
        hide: function() {
            this.$loaiing.removeClass("on full");
        }
    }

    module.exports = result;
});
